package com.wms.system.service.impl.wcs;

import com.alibaba.excel.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wms.common.utils.Assert;
import com.wms.system.domain.wcs.PackingExcelTemplate;
import com.wms.system.mapper.wcs.PackingExcelTemplateMapper;
import com.wms.system.service.wcs.IPackingExcelTemplateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
public class PackingExcelTemplateServiceImpl implements IPackingExcelTemplateService {
    @Autowired
    private PackingExcelTemplateMapper packingExcelTemplateMapper;


    public List<PackingExcelTemplate> queryList(PackingExcelTemplate packingExcelTemplate){
        return packingExcelTemplateMapper.selectList(new LambdaQueryWrapper<PackingExcelTemplate>()
                .like(StringUtils.isNotBlank(packingExcelTemplate.getTemplateName()),PackingExcelTemplate::getTemplateName,packingExcelTemplate.getTemplateName())
                .orderByDesc(PackingExcelTemplate::getCreateTime)
        );
    }

    public void insert(PackingExcelTemplate packingExcelTemplate){
        packingExcelTemplate.setId(null);
        packingExcelTemplate.setCreateTime(new Date());
        packingExcelTemplate.setUpdateTime(new Date());
        checkData(packingExcelTemplate);
        packingExcelTemplateMapper.insert(packingExcelTemplate);
    }

    public void update(PackingExcelTemplate packingExcelTemplate){
        packingExcelTemplate.setUpdateTime(new Date());
        checkData(packingExcelTemplate);
        packingExcelTemplateMapper.updateById(packingExcelTemplate);
    }

    public void delete(Long[] ids){
        packingExcelTemplateMapper.deleteBatchIds(Arrays.asList(ids));
    }

    private void checkData(PackingExcelTemplate packingExcelTemplate){
        PackingExcelTemplate exist = packingExcelTemplateMapper.selectOne(new LambdaQueryWrapper<PackingExcelTemplate>()
                .eq(PackingExcelTemplate::getTemplateName, packingExcelTemplate.getTemplateName())
                .ne(packingExcelTemplate.getId() != null, PackingExcelTemplate::getId, packingExcelTemplate.getId())
                .last("limit 1"));
        Assert.isNull(exist,"模板名称[{}]已存在", packingExcelTemplate.getTemplateName());
    }
}
